package util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class DBUtil {

    private  static DBUtil dbUtil = null;
    private Connection connection = null;
    private PreparedStatement statement = null;
    private ResultSet resultSet = null;

    private DBUtil(){
    }

    public static DBUtil getInstance(){
        if (dbUtil==null){
            return new DBUtil();
        }
        return dbUtil;
    }



    public PreparedStatement getStatement(String sql){
        connection = JDBCUtil.getConnection();

        try {
            return connection.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int  update(String sql, List<Object> param){
        try {
            statement = getStatement(sql);

            if (param!=null){

            for (int index=1;index<=param.size();index++) {
                statement.setObject(index,param.get(index-1));
            }
            }

            int result = statement.executeUpdate();

            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    public ResultSet query(String sql, List<Object> param){
        try {

            statement = getStatement(sql);
            if (param!=null) {
                for (int index = 1; index <= param.size(); index++) {
                    statement.setObject(index, param.get(index-1));
                }
            }
             resultSet = statement.executeQuery();

            return resultSet;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 关闭连接
     */
    public void clseRes(){
        try {
            if (connection != null) {
                connection.close();
            }

            if (statement != null) {
                statement.close();
            }
            if (resultSet!=null){
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
